<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        span{
            font-size: 12px;
            color: red;
            display: none;
        }
        img{
            margin-left: -30px;
        }
    </style>
</head>
<body>
    <div>
        用户名：<input type="text" id="user-name">
        <span>用户名为4-8位数字字母组合</span>
    </div>
    <div>
        密码：<input type="password" id="password">
        <img src="icon/eye_close.png" alt="">
        <span>密码要求8位以上，包含数字、字母、特殊字符</span>
    </div>
    <div>
        确认密码：<input type="password" >
        <img src="icon/eye_close.png" alt="">
        <span>两次密码输入不一致</span>
    </div>
    <button id="login">注册：</button>
<script>
    let usernameReg=/^\w{4,8}$/
    let passwordReg=/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{8,}$/
    let inputs = document.getElementsByTagName("input");
    let spans = document.getElementsByTagName("span");
    let login = document.getElementById("login");
    let eyes=document.getElementsByTagName("img");
    let flag = true;
    let flag1 = true;

    // 校验用户名
    inputs[0].onblur=function (){
        checkValue(usernameReg,0)
    }

    // 校验密码
    inputs[1].onblur=function (){
        checkValue(passwordReg,1);

        // 输入密码和确认密码两个有一个没填都不进行一致性判断
        checkSame();
    }

    // 二次密码验证
    inputs[2].onblur=checkSame;


    login.onclick=function (){
        if (usernameReg.test(inputs[0].value) && passwordReg.test(inputs[1].value) && inputs[1].value === inputs[2].value){
            alert("注册成功")
        }else {
            alert("注册失败")
        }
    }

    eyes[0].onclick=function (){
        switchEyes(0)
    }

    eyes[1].onclick=function (){
        switchEyes(1)
    }
    
    function checkValue(reg, index) {
        if (reg.test(inputs[index].value)){
            spans[index].style.display = "none"
        }else {
            spans[index].style.display = "inline"
        }
    }

    function checkSame(){
        // 输入密码和确认密码两个有一个没填都不进行一致性判断
        if (!inputs[1].value || !inputs[2].value){
            spans[2].style.display = "none";
            return;
        }
        if (inputs[1].value === inputs[2].value){
            spans[2].style.display = "none"
        }else{
            spans[2].style.display = "inline"
        }
    }

    function switchEyes(index){
        /*
            用布尔值来处理当前密码是否可见
         */
        let c = index?flag:flag1;
        console.log(c)
        if(c){
            eyes[index].src = "icon/eye_open.png";
            inputs[index+1].type = "text";
        }else {
            eyes[index].src = "icon/eye_close.png";
            inputs[index+1].type = "password";
        }
        if (index){
            flag = !flag;
        }else {
            flag1 = !flag1;
        }

    }

</script>
</body>
</html>